package com.miku.framework.ui.view;

import java.util.ArrayList;
import java.util.List;

import com.miku.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;

public class DashBoard extends TableLayout{
	private String align;
	private int columns;
	
	public DashBoard(Context context) {
		super(context);
		// TODO Falta implementar para cuando no se ingresa atributos por xml layout
	}
	
	public DashBoard(Context context, AttributeSet attrs) {
		super(context, attrs);

		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DashBoard);
		
		final int numAttributes = a.getIndexCount();
		
		for (int i=0; i<numAttributes; i++){
			switch (a.getIndex(i)){
				case R.styleable.DashBoard_align:
					align = a.getString(i);
				break;
				case R.styleable.DashBoard_columns:
					columns = a.getInteger(i, -1);
			}
		}
		a.recycle();

	}
	
	
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		List<Menu> arrMenus = new ArrayList<Menu>();
        int numChildren = this.getChildCount();
        
        int widthMaxChild = 0;
        int heightMaxChild = 0;
        for (int i=0; i<numChildren; i++){
        	Menu menu = (Menu)this.getChildAt(i);
        	arrMenus.add(menu);
        	int widthActual = menu.getMeasuredWidth();
        	int heightActual = menu.getMeasuredHeight();
        	if (widthActual > widthMaxChild)
        		widthMaxChild = widthActual;
        	if (heightActual > heightMaxChild)
        		heightMaxChild = heightActual;
        }
        
        int widthView = this.getMeasuredWidth();
        
        int widthComponents = widthMaxChild * columns;
        int totalSpace = widthView - widthComponents;
        int space = totalSpace / (columns - 1);
        int spaceHeight = 20;
        
        Log.i("DashBoardActivity","WidthView: " + widthView);
        Log.i("DashBoardActivity","WidthMaxChild: " + widthMaxChild);
        Log.i("DashBoardActivity","Space: " + space);
        
        //this.removeAllViews();
        
        
        
        //this.layout( l,  t,  r,  b);
        
        int y = 0 ;//+ (spaceHeight/2);
        int x = 0;
        
        for (int i=0; i<numChildren; i++){
        	Menu menu = arrMenus.get(i);
        	
        	menu.layout(x, y, x + space + widthMaxChild , y + heightMaxChild);
        	x += space + widthMaxChild;
        	if ((i+1)%columns ==0 ){
        		
				y += widthMaxChild + spaceHeight  ;
				x = 0;
				Log.i("DashBoard","Cambio de linea");
				
        	}
        	
    			
        }
        
	}
	
	@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

}
